<?php
class Paycallback extends BZ_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('api', 'common'));
        $this->load->library('chinapay/chinapay', null, 'chinapay');
        $this->load->library('alipay/alipaypc', null, 'alipaypc');
        $this->load->library('ccbpay/ccbpay', null, 'ccbpay');
        $this->load->library('alidayu/alidayusms', null, 'alidayusms');
        $this->load->library('swiftpass/swiftpay', null, 'swiftpay');
        $this->load->model('pay_record_model','pay_record');
        $this->load->model('order_base_model','order_base');
        $this->load->model('goods_base_model','goods_base');
        $this->load->model('order_profit_model','order_profit');
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model','user_account');
        $this->load->model('goods_map_cpt_model','goods_map_cpt');
        $this->load->model('order_send_model','order_send');
        $this->load->model('pay_method_model', 'pay_method');
        $this->load->model('account_log_model', 'account_log');
        $this->load->model('pay_failure_log_model', 'pay_failure_log');
        $this->load->model('order_send_model', 'order_send');
        $this->load->model('macs_model', 'macs');
        $this->load->model('ym_sms_error_model', 'ym_sms_error');
        $this->load->model('user_transfer_charge_model', 'user_transfer_charge');
        $this->load->model('bind_user_model', 'bind_user');
    }
    
    /**
     * 支付宝支付
     * 异步回调函数。 ok
     */
    public function alipayNotify()
    {
        $response = $this->alipaypc->responseAlipayNotify();
        $payId = $response;
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            return ;
            //$this->jsonMessage('订单信息有误，或长时间未支付');
        }
        $payRecord = $result->row(0);
        if ($response) { //$response付款成功；
            if ((int)$payRecord->bit_state&65536) { //如果支付过
                return ;
                //$this->jsonMessage('该订单已经支付过');
            }
    
            $result2 = $this->order_base->findByPayId($payId);
            if ($result2->num_rows() <= 0) {
                return ;
                //$this->jsonMessage('订单信息有误，或长时间未支付哦');
            }
            $orderBase = $result2->result();
    
            $result3 = $this->user->findByIds(array('uid'=>$payRecord->uid));
            if ($result3->num_rows() <= 0) {
                return ;
                //$this->jsonMessage('当前购买者用户异常');
            }
            $user = $result->row(0);
    
            $this->db->trans_begin();
            //更新支付状态
            $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'bit_state'=>65536, 'pay_time'=>time()));
            //$orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536));
			$orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536, 'paytime'=>time()));

            //扣除金币支付的金额
            if ($payRecord->order_bouns > 0) {
                $updateAccount = $this->user_account->updateUserAccount($payRecord->uid, array('amount_bonus'=>-$payRecord->order_bouns));
                if (!$updateAccount) {
                    $this->db->trans_rollback();
                    return ;
                    //$this->jsonMessage('扣除金币失败！');
                }
            }
    
            $payProfit = array(); //如果是支付后分润，则执行分润操作
            foreach ($orderBase as $key=>$order) {
                if ((int)$order->bit_opt&4) { //需要支付后分润的订单
                    $payProfit[$order->order_id] = $order;
                }
                //支付后减去库存，更新已售数量
                $update = $this->goods_base->setTicketStock(array('goods_id'=>$order->goods_id, 'sold_number'=>$order->goods_num, 'limit_number'=>-$order->goods_num));
            }
            if (!empty($payProfit)) {
                $error = $this->orderExecuteProfit($payProfit);
                if (!empty($error)) {
                    $this->db->trans_rollback();
                    return ;
                    //$this->jsonMessage($error);
                }
            }
    
            if (!$updatePay || !$orderUpdate) {
                $this->db->trans_rollback();
                return ;
                //$this->jsonMessage('操作失败！');
            }
    
            $this->sendOrderBaseMessage($orderBase, $user); //给订单发送短信
    
            $this->db->trans_commit();
            
            //推送支付延迟 的订单到机器
            $this->sendOrderToMac($payRecord, $orderBase[0]->sid);
            
            //获得接口对接产品,进行对接
            $this->autoDockingApi($payRecord);
    
        } else {
            $result = $this->pay_failure_log->findByOrderSn($payId);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $this->input->post(), array('status'=>$response));
            }
        }
    }
    
    /**
     * 银联支付
     * 异步回调函数，主订单pay_id
     */
    public function chinapayNotify()
    {
        $postData = $this->input->post();
        $response = $this->chinapay->responseChinapayApi($postData);
        $payId = $this->input->post('orderno');
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            $this->jsonMessage('订单信息有误，或长时间未支付');
        }
        $payRecord = $result->row(0);
    
        if ($response === true) { //$response付款成功；
            if ((int)$payRecord->bit_state&65536) { //如果支付过
                $this->jsonMessage('该订单已经支付过');
            }
    
            $result2 = $this->order_base->findByPayId($payId);
            if ($result2->num_rows() <= 0) {
                $this->jsonMessage('订单信息有误，或长时间未支付哦');
            }
            $orderBase = $result2->result();
    
            $result3 = $this->user->findByIds(array('uid'=>$payRecord->uid));
            if ($result3->num_rows() <= 0) {
                $this->jsonMessage('当前购买者用户异常');
            }
            $user = $result->row(0);
    
            $this->db->trans_begin();
            //更新支付状态
            $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'bit_state'=>65536, 'pay_time'=>time()));
            //$orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536));
			$orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536, 'paytime'=>time()));
    
            //扣除金币支付的金额
            if ($payRecord->order_bouns > 0) {
                $updateAccount = $this->user_account->updateUserAccount($payRecord->uid, array('amount_bonus'=>-$payRecord->order_bouns));
                if (!$updateAccount) {
                    $this->db->trans_rollback();
                    $this->jsonMessage('扣除金币失败！');
                }
            }
    
            $payProfit = array(); //如果是支付后分润，则执行分润操作
            foreach ($orderBase as $key=>$order) {
                if ((int)$order->bit_opt&4) { //需要支付后分润的订单
                    $payProfit[$order->order_id] = $order;
                }
                //支付后减去库存，更新已售数量
                $update = $this->goods_base->setTicketStock(array('goods_id'=>$order->goods_id, 'sold_number'=>$order->goods_num, 'limit_number'=>-$order->goods_num));
            }
            if (!empty($payProfit)) {
                $error = $this->orderExecuteProfit($payProfit);
                if (!empty($error)) {
                    $this->db->trans_rollback();
                    $this->jsonMessage($error);
                }
            }
    
            if (!$updatePay || !$orderUpdate) {
                $this->db->trans_rollback();
                $this->jsonMessage('操作失败！');
            }
    
            $this->sendOrderBaseMessage($orderBase, $user); //给订单发送短信
    
            $this->db->trans_commit();

            //推送支付延迟 的订单到机器
            $this->sendOrderToMac($payRecord, $orderBase[0]->sid);
            
            //获得接口对接产品,进行对接
            $this->autoDockingApi($payRecord);
    
        } else {
            $result = $this->pay_failure_log->findByOrderSn($payId);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $postData, array('status'=>$response));
            }
        }
    }
    
    /* 微信jsapi支付回调*/
    public function wxNotify()
    {
        include_once(getcwd()."/application/libraries/scenicwxpay/WxPayPubHelper/WxPayPubHelper.php");
        $notify = new Notify_pub();//使用通用通知接口
        $xml    = file_get_contents('php://input', 'r');   //存储微信的回调
        $notify->saveData($xml);

        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        $checkSign = $notify->checkSign();
        if ($checkSign == FALSE) {
            $notify->setReturnParameter("return_code","FAIL");  //返回状态码
            $notify->setReturnParameter("return_msg","签名失败");  //返回信息
        } else {
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;      //echo为微信返回值   不能更改   不能删除
        
        if ($checkSign == FALSE) {
            return ;
        }
        
        $payId = $notify->data['out_trade_no'];
        
        if ($notify->data["return_code"] == "FAIL" || $notify->data["result_code"] == "FAIL") {
            $return_param = "【通信出错】【业务出错】:\n".$xml."\n";
            $result = $this->pay_failure_log->findByOrderSn($payId);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $return_param, "微信支付报错");
            }
        } else {
            $result = $this->pay_record->findByPayId($payId);
            if ($result->num_rows() <= 0) {
                return ;
            }
            $payRecord = $result->row(0);
            
            if ((int)$payRecord->bit_state&65536) { //如果支付过
                $this->redirect($this->config->wap_base_url. 'scenic/payment/paySuccess/'.$payRecord->pay_id.'.html');
            }
            
            $result2 = $this->order_base->findByPayId($payId);
            if ($result2->num_rows() <= 0) {
                $this->payError('订单信息有误，或长时间未支付');
                return ;
            }
            $orderBase = $result2->result();
            
            $this->db->trans_begin();
            //更新支付状态
            $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'bit_state'=>65536, 'pay_time'=>time()));
            //$orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536));
			$orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536, 'paytime'=>time()));
            
            //扣除金币支付的金额
            if ($payRecord->order_bouns > 0) {
                $updateAccount = $this->user_account->updateUserAccount($payRecord->uid, array('amount_bonus'=>-$payRecord->order_bouns));
                if (!$updateAccount) {
                    $this->db->trans_rollback();
                    $this->payError('扣除金币失败！');
                    return ;
                }
            }
            
            $payProfit = array(); //如果是支付后分润，则执行分润操作
            foreach ($orderBase as $key=>$order) {
                if ((int)$order->bit_opt&4) { //需要支付后分润的订单
                    $payProfit[$order->order_id] = $order;
                }
                //支付后减去库存，更新已售数量
                $update = $this->goods_base->setTicketStock(array('goods_id'=>$order->goods_id, 'sold_number'=>$order->goods_num, 'limit_number'=>-$order->goods_num));
            }
            if (!empty($payProfit)) {
                $error = $this->orderExecuteProfit($payProfit);
                if (!empty($error)) {
                    $this->db->trans_rollback();
                    $this->jsonMessage($error);
                }
            }
            
            if (!$updatePay || !$orderUpdate) {
                $this->db->trans_rollback();
                $this->payError('操作失败！');
                return ;
            }
            
            $this->sendOrderBaseMessage($orderBase); //给订单发送短信
            
            $this->db->trans_commit();
            
            //推送支付延迟 的订单到机器
            $this->sendOrderToMac($payRecord, $orderBase[0]->sid);
            
            //获得接口对接产品,进行对接
            $this->autoDockingApi($payRecord);
        }
    }

    /**
     * 建行异步
     * 异步回调函数。 ok
     */
    public function ccbNotify()
    {
        $response = $this->ccbpay->responseCcbNotify();
        $payId = $this->input->post('ORDERID', true);
        $this->pay_failure_log->insertPayFailureLog($payId, '', array('status'=>'建设银行异步进来了'));
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            return ;
        }

        $payRecord = $result->row(0);
        if ($response === TRUE) { //$response付款成功；
            if ((int)$payRecord->bit_state&65536) { //如果支付过
                return ;
                //$this->jsonMessage('该订单已经支付过');
            }
    
            $result2 = $this->order_base->findByPayId($payId);
            if ($result2->num_rows() <= 0) {
                return ;
                //$this->jsonMessage('订单信息有误，或长时间未支付哦');
            }
            $orderBase = $result2->result();
    
            $result3 = $this->user->findByIds(array('uid'=>$payRecord->uid));
            if ($result3->num_rows() <= 0) {
                return ;
                //$this->jsonMessage('当前购买者用户异常');
            }
            $user = $result->row(0);
    
            $this->db->trans_begin();
            //更新支付状态
            $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'bit_state'=>65536, 'pay_time'=>time()));
            //$orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536));
			$orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536, 'paytime'=>time()));

            //扣除金币支付的金额
            if ($payRecord->order_bouns > 0) {
                $updateAccount = $this->user_account->updateUserAccount($payRecord->uid, array('amount_bonus'=>-$payRecord->order_bouns));
                if (!$updateAccount) {
                    $this->db->trans_rollback();
                    return ;
                }
            }
    
            $payProfit = array(); //如果是支付后分润，则执行分润操作
            foreach ($orderBase as $key=>$order) {
                if ((int)$order->bit_opt&4) { //需要支付后分润的订单
                    $payProfit[$order->order_id] = $order;
                }
                //支付后减去库存，更新已售数量
                $update = $this->goods_base->setTicketStock(array('goods_id'=>$order->goods_id, 'sold_number'=>$order->goods_num, 'limit_number'=>-$order->goods_num));
            }
            if (!empty($payProfit)) {
                $error = $this->orderExecuteProfit($payProfit);
                if (!empty($error)) {
                    $this->db->trans_rollback();
                    return ;
                }
            }
    
            if (!$updatePay || !$orderUpdate) {
                $this->db->trans_rollback();
                return ;
            }
    
            $this->sendOrderBaseMessage($orderBase, $user); //给订单发送短信
    
            $this->db->trans_commit();
            
            //推送支付延迟 的订单到机器
            $this->sendOrderToMac($payRecord, $orderBase[0]->sid);
            
            //获得接口对接产品,进行对接
            $this->autoDockingApi($payRecord);
    
        } else {
            $result = $this->pay_failure_log->findByOrderSn($payId);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $this->input->post(), array('status'=>$this->ccbpay->getMessage()));
            }
        }
    }
    
    /**
     * 兴业银行(威富通)异步
     * 异步回调函数。 ok
     */
    public function swiftNotify()
    {
        $payId = $this->swiftpay->getOutTradeNo();
        $result = $this->pay_record->findByPayId($payId);
        if ($result->num_rows() <= 0) {
            return ;
        }

        $payRecord = $result->row(0);
        if ((int)$payRecord->bit_state&65536) { //如果支付过
            return ;
        }

        $result2 = $this->order_base->findByPayId($payId);
        if ($result2->num_rows() <= 0) {
            return ;
        }
        $orderBase = $result2->result();

        $swiftParam = $this->user_transfer_charge->findBySid($orderBase[0]->sid);
        if ($swiftParam->num_rows() == 0) { //账号未绑定银行参数
            return ;
        }
        $swiftParam = $swiftParam->row();

        $response = $this->swiftpay->callback($swiftParam->key);
        if ($response['status'] == 0 && $response['result_code'] == 0) { //$response付款成功；
            $result3 = $this->user->findByIds(array('uid'=>$payRecord->uid));
            if ($result3->num_rows() <= 0) {
                return ;
                //$this->jsonMessage('当前购买者用户异常');
            }
            $user = $result3->row(0);

            $this->db->trans_begin();
            //更新支付状态
            $updatePay = $this->pay_record->updatePayRecord(array('pay_id'=>$payId, 'bit_state'=>65536, 'serial_number' => $response['transaction_id'], 'pay_method' => 188, 'pay_time'=>time()));
            //$orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536));
            $orderUpdate = $this->order_base->updateByOrderPayId(array('pay_id'=>$payId, 'bit_pay'=>65536, 'pay_method' => 188, 'paytime'=>time()));

            //扣除金币支付的金额
            if ($payRecord->order_bouns > 0) {
                $updateAccount = $this->user_account->updateUserAccount($payRecord->uid, array('amount_bonus'=>-$payRecord->order_bouns));
                if (!$updateAccount) {
                    $this->db->trans_rollback();
                    return ;
                }
            }

            $payProfit = array(); //如果是支付后分润，则执行分润操作
            foreach ($orderBase as $key=>$order) {
                if ((int)$order->bit_opt&4) { //需要支付后分润的订单
                    $payProfit[$order->order_id] = $order;
                }
                //支付后减去库存，更新已售数量
                $update = $this->goods_base->setTicketStock(array('goods_id'=>$order->goods_id, 'sold_number'=>$order->goods_num, 'limit_number'=>-$order->goods_num));
            }
            if (!empty($payProfit)) {
                $error = $this->orderExecuteProfit($payProfit);
                if (!empty($error)) {
                    $this->db->trans_rollback();
                    return ;
                }
            }
    
            if (!$updatePay || !$orderUpdate) {
                $this->db->trans_rollback();
                return ;
            }
    
            $this->sendOrderBaseMessage($orderBase, $user); //给订单发送短信
    
            $this->db->trans_commit();
            
            //推送支付延迟 的订单到机器
            $this->sendOrderToMac($payRecord, $orderBase[0]->sid);
            
            //获得接口对接产品,进行对接
            $this->autoDockingApi($payRecord);

        } else {
            $result = $this->pay_failure_log->findByOrderSn($payId);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($payId, $response, array('status'=>'兴业银行异步回调支付'));
            }
        }
    }


    /**
     * 给景区订单发送短信
     * @param unknown $orderBase
     */
    private function sendOrderBaseMessage($orderBase, $user)
    {
        foreach ($orderBase as $k=>$item) {
            //如果是深大(智游宝)接口、九天科技(票付通)接口、皇家海洋馆接口、哈尔滨极地馆接口、银科环企(大汖温泉、梦幻海、热高)接口、联动票务接口、深大(智游宝)新接口、千朝农谷接口、畅游通(武当山、云丘山、善卷洞、圣井山、哈尔滨极地馆)接口、驴妈妈接口、青海湖接口、票付通（九天科技）新接口、天时同城接口时，着想不发短信
            if (!in_array($item->api_id, array(1, 4, 5, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24))) {
                $smsParam = array();
                $period = ' 出游日期：'.date('Y-m-d', $item->plantime);
                if (empty($item->start_time) && empty($item->end_time)) {
                    $startTime = $item->start_time ? $item->start_time : date('Y-m-d');
                    $endTime = $item->end_time ? $item->end_time : date('Y-12-31');
                    $period = ' 有效期'.$startTime.'至'.$endTime;
                }
                $smsParam['msg'] = $item->provider_name.'-'.$item->goods_name.$item->goods_num;

                if ($item->calculate_method == 3) {
                    $smsParam['order'] = $item->order_id.'），'.$period;
                    $smsParam['payId'] = $item->pay_id;
                    $smsTemplateCode = 'SMS_53550036';
                    //$message = '您已成功预订了'.$item->provider_name.'-'.$item->goods_name.$item->goods_num.'张（订单号：'.$item->order_id.'），'.$period.'，凭订票身份证或订单二维码入园。点击http://wap.zxkj918.com/scenic/order/index 查看订单二维码,如有疑问详询400-0571-648，登录http://wap.zxkj918.com下载APP了解更多产品。';
                } else {
                    if (strlen($item->sfz)<15) { //短信验证码
                        $smsParam['order'] = $item->order_id;
                        $smsParam['code'] = $item->sfz;
                        $smsTemplateCode = 'SMS_37135040';
                        //$message = '您已成功预订了'.$item->provider_name.'-'.$item->goods_name.$item->goods_num.'张（订单号：'.$item->order_id.'），验证码:'.$item->sfz.$period.'，如有疑问请致电400-0571-648。';
                    } else {
                        $smsParam['order'] = $item->order_id.'），'.$period;
                        $smsTemplateCode = 'SMS_37125088';
                        //$message = '您已成功预订了'.$item->provider_name.'-'.$item->goods_name.$item->goods_num.'张（订单号：'.$item->order_id.'），'.$period.'，凭订票身份证入园。如需换票或选择到景区支付,可在景区指定地点换票，如有疑问请致电400-0571-648。';
                    }
                }
                if ($user->sms == 1) { //表示短信带后缀名称
                    $smsParam['payer_name'] = '400-0571-648。-'.$item->payer_name;
                    //$message = $message.'-'.$item->payer_name;
                } else {
                    $smsParam['payer_name'] = '400-0571-648。';
                }
                //$this->sendToSms($item->phone, $message, 2);
                $alidayusms = $this->alidayusms->smsNumSend($item->phone, json_encode($smsParam), $smsTemplateCode);
                if (isset($alidayusms['success']) && $alidayusms['success'] == 'false') {
                    $this->ym_sms_error->insertYmSmsError($item->phone, json_encode($smsParam), json_encode($alidayusms), 4);
                }
            }
        }
    }
    
    /**
     * 对接接口
     * @param unknown $payRecord
     */
    private function autoDockingApi($payRecord)
    {
        //初始化o_api_id_ary和o_goods_id_ary
        $o_api_id_ary = array();
        $o_goods_id_ary = array();
        
        //获得产品id
        $goodsIdsAry = unserialize($payRecord->goods_ids);
        //获得订单id
        $orderIdsAry = unserialize($payRecord->order_ids);
        //根据产品id查询接口对接信息
        $goodsBaseWhere = array('goods_ids'=>$goodsIdsAry);
        $goodsBaseQuery = $this->goods_base->findByParams($goodsBaseWhere);
        $goodsBaseResult = $goodsBaseQuery->result();
        foreach ($goodsBaseResult as $key => $goodsBaseRow) {
            $o_api_id = $goodsBaseRow->o_api_id;
            $o_goods_id = $goodsBaseRow->o_goods_id;
            
            if (!empty($o_api_id) && !empty($o_goods_id)) {
                array_push($o_api_id_ary, $o_api_id);//给$o_api_id_ary赋值
                array_push($o_goods_id_ary, $o_goods_id);//给$o_goods_id_ary赋值
            }
        }
        
        //如果有$o_api_id_ary、$o_goods_id_ary和$orderIdsAry,就自动对接
        if ($o_api_id_ary && $o_goods_id_ary && $orderIdsAry) {
            $params = array(
                'o_type'         => 1,//表示下单
                'o_api_id_ary'   =>$o_api_id_ary,
                'o_goods_id_ary' => $o_goods_id_ary,
                'order_id_ary'   => $orderIdsAry,
            );
            $curlPost = 'params='.json_encode($params);
            
            //$url = $this->config->www_base_url.'api/api';//对外接口地址(用于接他网接口)
			$url = $this->config->api_base_url.'api';//对外接口地址(用于接他网接口)
            getApiDynamic($curlPost, $url);
        }
    }
    
    /**
     * 处理景区订单机器漏单：
     * 1，A用户订单先买票，但没有支付
     * 2，然后B用户购买，完成支付
     * 3，A用户支付完成
     * 处理办法：
     * 在付款完成后，加入判断： 查询该景区订单最大一个订单，
     * 如果现在现在支付的订单小于最大订单，就在订单推送表（order_send）加一条
     * 如果大于不用操作
     **/
    private function sendOrderToMac($payRecord, $sid)
    {
        $result = $this->order_base->findMaxOrderId($payRecord->pay_id, $sid);
        if ($result->num_rows() > 0) {
            $macs = $this->macs->findBySid($sid);
            if ($macs->num_rows() > 0) {
                $orderIds = unserialize($payRecord->order_ids);
                if ( ! empty($orderIds) && is_array($orderIds)) {
                    $this->order_send->addBatch($orderIds, $macs->result());
                }
            }
        }
        
        //微信购买成功提醒
        $openUser = $this->purchaseSuccess($payRecord);
    }
    
    /**
     * 微信授权
     */
    public function purchaseSuccess($payRecord)
    {
        $result = $this->bind_user->findByOpenOrAli($payRecord->uid);
        if ($result->num_rows() <= 0) {
            return false;
        }
        $bindUser = $result->row(0);
        $openId = $bindUser->open_id;
        if ($this->input->get('payId')) {//测试用的传参
            $result1 = $this->pay_record->findByPayId($this->input->get('payId'));
            if ($result1->num_rows() <= 0) {
                return false;
            }
            $payRecord = $result1->row(0);
        }
        include_once(APPPATH.'libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php');
        $jsapi = new JsApi_pub();
        $accessToken = $jsapi->getAccessToken();
        if (isset($accessToken->errcode)) {
            return $accessToken->errmsg;
        }
        $urlOne = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$accessToken->access_token;
        $data['touser']           = $openId;
        $data['template_id']      = 'zFSPosWPThOgUiZcu7ywOBfHgikG6n-Sj1slBhyVQqw';
        $data['url']              = $this->config->wap_base_url.'scenic/order/index.html';
        $data['data']['first']    = array('value' => '恭喜您，付款成功了','color' => '#173177');;
        $data['data']['keyword1'] = array('value' => $payRecord->body,'color' => '#173177');
        $data['data']['keyword2'] = array('value' => $payRecord->pay_id,'color' => '#173177');
        $data['data']['keyword3'] = array('value' => $payRecord->amount,'color' => '#173177');
        $data['data']['keyword4'] = array('value' => date('Y-m-d H:i'),'color' => '#173177');
        $data['data']['remark']   = array('value' => '感谢您的光临，欢迎再次购买！','color' => '#173177');
        $res = json_decode(getApiDynamic(json_encode($data), $urlOne));
        if ($res->errcode != 0) {
            return false;
        }
        return TRUE;
    }
}

